<template>
  <div class="header-lay" :style="styles">
    <el-avatar :src="logo" shape="square" :size="20" :fit="'fill'"
               class="header-logo"/>
    <div class="page-title"> {{ title }}</div>
    <div style="height: 48px;">
      <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="horizontal"
          :ellipsis="false"
          style="flex:1; border: none; height: 32px;margin: 8px 4px 8px;"
          background-color="#252A2F"
          text-color="#C7C8CA"
          active-text-color="#FFFFFF"
          @select="handleSelect">
        <template v-for="(item) in menus" :key="item.path">
          <el-menu-item style="margin-right: 20px;" :index="item.routePath">
            <el-icon :size="16">
              <component :is="item.icon"></component>
            </el-icon>
            <template #title>
              <span>
                {{ item.name }}
              </span>
            </template>
          </el-menu-item>
        </template>
      </el-menu>
    </div>

    <div class="flex-lay"/>
    <div class="right-lay">
      <el-dropdown @command="handleCommand" class="right-menu-item hover-effect" trigger="click">
        <div class="avatar-wrapper">
          <img style="width: 20px;height: 20px;margin-right: 16px" src="@/assets/moren@2x.png">
          <div class="userName">
            {{ user?.nickName || user?.name }}
          </div>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <!-- <router-link to="/user/profile">
              <el-dropdown-item>个人中心</el-dropdown-item>
            </router-link> -->
            <el-dropdown-item>
              <span @click="updatePwd()">修改密码</span>
            </el-dropdown-item>
            <el-dropdown-item divided command="logout">
              <span>退出登录</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 修改密码弹窗 -->
    <el-dialog v-model="dialogVisibleUpdatePwd" title="修改密码" width="500">
      <el-form ref="pwdRef" :model="updatePwdForm" :rules="rules" label-width="82px">
        <el-form-item label="旧密码：" prop="oldPwd">
          <el-input
              v-model="updatePwdForm.oldPwd"
              placeholder="请输入旧密码"
              clearable
              :style="{ width: '96%' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码：" prop="newPwd">
          <el-input
              v-model="updatePwdForm.newPwd"
              placeholder="请输入新密码"
              clearable
              :style="{ width: '96%' }"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelForm()">取消</el-button>
        <el-button type="primary" @click="submitForm()"> 确定</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script lang="ts" setup>

import {computed, reactive, ref, toRefs} from "vue";
import {Md5} from 'ts-md5'
import router from "@/router";
import {updatePassword, userLogout} from "@/apis/sop/uni-auth";
import {ElMessageBox} from "element-plus";
import {msgInfo, msgWarn} from "@/utils/InfoUtil";

interface Props {
  logo: string,
  title?: string,
  headHei: number,
  menus?: MenuType[],
  user?: UserType
}

const props = defineProps<Props>();
const pwdRef = ref();
const activeIndex = ref('0');

const dialogVisibleUpdatePwd = ref<boolean>(false)

const rules: any = {
  oldPwd: [{required: true, message: '旧密码不能为空', trigger: 'blur'}],
  newPwd: [
    {required: true, message: '新密码不能为空', trigger: 'blur'},
    {min: 8, max: 16, message: '长度在 8 到 16 个字符', trigger: 'blur'},
    {
      pattern:
          /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z0-9`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·]{8,16}$/,
      message: '支持字母、数字、英文字符，至少包含一个大写字母一个小写字母和数字，长度8-16位',
      trigger: 'blur'
    }
  ]
}

const data = reactive({
  updatePwdForm: {
    oldPwd: '',
    newPwd: ''
  }
})

const {updatePwdForm} = toRefs(data)

const handleSelect = (key: string, keyPath: string[]) => {
  if (!router.currentRoute.value.path.startsWith(key)) {
    router.push({
      path: key
    })
  }
}

const skipToLogin = () => {
  window.location.href = window.location.origin
}

const logout = () => {
  ElMessageBox.confirm('确定退出系统吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res: any = await userLogout()
    //  退出成功清除token
    if (res.code == 0) {
      localStorage.removeItem('user-token');
    }
    skipToLogin();
  })
}

const handleCommand = (command: any) => {
  switch (command) {
    case 'logout':
      logout()
      break
    default:
      break
  }
}

const updatePwd = async () => {
  dialogVisibleUpdatePwd.value = true
  if (pwdRef.value) {
    pwdRef.value.resetFields()
  }
}

const cancelForm = () => {
  dialogVisibleUpdatePwd.value = false
}

const encMd5 = (pwd: string) => {
  const md5: any = new Md5()
  md5.appendAsciiStr(pwd)
  return md5.end()
}

const submitForm = async () => {
  pwdRef.value.validate(async (valid: any) => {
    if (valid) {
      const oldPwd = encMd5(updatePwdForm.value.oldPwd)
      const newPwd = encMd5(updatePwdForm.value.newPwd)

      let dto = {
        oldPwd: oldPwd,
        newPwd: newPwd
      }

      const res: any = await updatePassword(dto)
      if (res.code == 0) {
        dialogVisibleUpdatePwd.value = false
        msgInfo('密码修改成功')
        // 清除token 退出到登录页面
        localStorage.removeItem("user-token");
        window.location.href = window.location.origin
      } else {
        return msgWarn(res.message)
      }
    }
  })
}

const styles = computed(() => {
  return {
    "color": "white",
    "font-size": "14px",
    "height": props.headHei + 'px',
  };
});

</script>

<style scoped>
.el-menu--horizontal > .el-menu-item {
  border-bottom: none;
  text-decoration: none;
  padding: 0 8px;
  margin-right: 20px;
  background-color: rgba(0, 0, 0, 0) !important;

  opacity: .8;
  color: #efeff1;
  font-size: 13px;
  will-change: opacity, background-color;
  -webkit-transition: opacity .3s, background-color .3s;
  transition: opacity .3s, background-color .3s;
}

.el-menu--horizontal > .el-menu-item.is-active {
  border-radius: 4px;
  padding: 0 8px;
  border-bottom: none;
  text-decoration: none;
  opacity: 1;
  background-color: #333844 !important;
}

.el-menu--horizontal > .el-menu-item:hover {
  border-radius: 4px;
  padding: 0 8px;
  border-bottom: none;
  text-decoration: none;
  opacity: 1;
  background-color: #333844 !important;
}

.header-lay {
  display: flex;
  flex-direction: row;
  align-items: center;
  height: auto;
  padding: 0 16px 0;
  font-size: 13px;
  font-weight: 400;
  z-index: 99;
  background-color: #ffffff;
  -webkit-box-shadow: 0 2px 9px 0 rgba(0,0,0,.05);
  box-shadow: 0 2px 9px 0 rgba(0,0,0,.05);
}

.header-logo {
  text-align: left;
  margin-right: 16px;
}

.page-title {
  text-align: left;
  font-size: 14px;
  font-weight: bold;
  color: #666666;
  margin-right: 16px;
}

.avatar-wrapper {
  display: flex;
  cursor: pointer;
  align-items: center;
  font-size: 13px;
  color: #666666;
}

.flex-lay {
  flex: 1;
}

.right-lay {
  display: flex;
  flex-direction: row;
  margin-right: 4px;
  align-items: center;
}

.userName {
  font-weight: bold;
}

</style>
